﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using MPMovieCatalog.Configuration;
using MPMovieCatalog.Domain;
using MPMovieCatalog.Forms;
using MPMovieCatalog.Service;
using MPMovieCatalog.Util;

namespace MPMovieCatalog.Export.Forms
{
    public partial class TextExportForm : Form
    {
        private List<RadioButton> m_moviesButtonGroup = new List<RadioButton>();
        private List<RadioButton> m_delimeterButtonGroup = new List<RadioButton>();
        private List<RadioButton> m_qualifierButtonGroup = new List<RadioButton>();
        private List<RadioButton> m_lineBreaksButtonGroup = new List<RadioButton>();

        public TextExportForm()
        {
            InitializeComponent();
            UpdateUI();

            m_moviesButtonGroup.Add(allMoviesRadioButton);
            m_moviesButtonGroup.Add(selectedMoviesRadioButton);

            m_delimeterButtonGroup.Add(semicolonRadioButton);
            m_delimeterButtonGroup.Add(commaRadioButton);
            m_delimeterButtonGroup.Add(tabRadioButton);
            m_delimeterButtonGroup.Add(spaceRadioButton);

            m_qualifierButtonGroup.Add(doubleQuoteRadioButton);
            m_qualifierButtonGroup.Add(singleQuoteRadioButton);
            m_qualifierButtonGroup.Add(noneRadioButton);

            m_lineBreaksButtonGroup.Add(replaceSpaceRadioButton);
            m_lineBreaksButtonGroup.Add(replaceNewLineRadioButton);
            m_lineBreaksButtonGroup.Add(replaceNoneRadioButton);
        }

        public ArrayList SelectedMovies { get; set; }

        public long AllMoviesCount { get; set; }

        private void TextExportForm_Load(object sender, EventArgs e)
        {
            ConfigurationWrapper wrapper = new ConfigurationWrapper();
            fileTextBox.Text = wrapper.TextExportSection.FileName;
            fieldNamesCheckBox.Checked = wrapper.TextExportSection.IsFieldNamesIncluded;

            SetSelectedIndex(m_moviesButtonGroup, wrapper.TextExportSection.Movies);
            SetSelectedIndex(m_delimeterButtonGroup, wrapper.TextExportSection.Delimeter);
            SetSelectedIndex(m_qualifierButtonGroup, wrapper.TextExportSection.Qualifier);
            SetSelectedIndex(m_lineBreaksButtonGroup, wrapper.TextExportSection.LineBreaks);

            allMoviesRadioButton.Text = string.Format(ResourceUtils.GetString("export", 1), AllMoviesCount);
            selectedMoviesRadioButton.Text = string.Format(ResourceUtils.GetString("export", 2), SelectedMovies == null ? 0 : SelectedMovies.Count);

            EncodingInfo[] encodingInfos = Encoding.GetEncodings();
            Array.Sort(encodingInfos, this.CompareEncodingInfo);

            encodingComboBox.DataSource = encodingInfos;
            encodingComboBox.DisplayMember = "DisplayName";

            string encodingName = wrapper.TextExportSection.Encoding;
            foreach (EncodingInfo encodingInfo in encodingInfos)
            {
                if (encodingInfo.Name == encodingName)
                {
                    encodingComboBox.SelectedItem = encodingInfo;
                    break;
                }
            }
        }

        private void browseButton_Click(object sender, EventArgs e)
        {
            if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
            {
                fileTextBox.Text = saveFileDialog.FileName;
            }
        }

        private void fieldsButton_Click(object sender, EventArgs e)
        {
            using (FieldsForm fieldsForm = new FieldsForm())
            {
                ConfigurationWrapper wrapper = new ConfigurationWrapper();
                fieldsForm.SelectedFields = wrapper.TextExportSection.Fields;

                if (fieldsForm.ShowDialog(this) == DialogResult.OK)
                {
                    wrapper.TextExportSection.Fields = fieldsForm.SelectedFields;
                    wrapper.SaveConfiguration();
                }
            }
        }

        private void TextExportForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            ConfigurationWrapper wrapper = new ConfigurationWrapper();
            wrapper.TextExportSection.FileName = fileTextBox.Text;
            wrapper.TextExportSection.Encoding = ((EncodingInfo)encodingComboBox.SelectedItem).Name;
            wrapper.TextExportSection.IsFieldNamesIncluded = fieldNamesCheckBox.Checked;
            wrapper.TextExportSection.Movies = GetSelectedIndex(m_moviesButtonGroup);
            wrapper.TextExportSection.Delimeter = GetSelectedIndex(m_delimeterButtonGroup);
            wrapper.TextExportSection.Qualifier = GetSelectedIndex(m_qualifierButtonGroup);
            wrapper.TextExportSection.LineBreaks = GetSelectedIndex(m_lineBreaksButtonGroup);

            wrapper.SaveConfiguration();

        }

        private void SetSelectedIndex(List<RadioButton> buttonGroup, int index)
        {
            if (index >= 0 && index < buttonGroup.Count)
            {
                buttonGroup[index].Checked = true;
            }
        }

        private int GetSelectedIndex(List<RadioButton> buttonGroup)
        {
            int index = -1;
            foreach (RadioButton radioButton in buttonGroup)
            {
                if (radioButton.Checked)
                {
                    index = buttonGroup.IndexOf(radioButton);
                }
            }
            return index;
        }

        private void exportButton_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(fileTextBox.Text))
            {
                MessageBox.Show(this, ResourceUtils.GetString("export", 8), ResourceUtils.GetString("common", 3), MessageBoxButtons.OK, MessageBoxIcon.Warning);
                fileTextBox.Focus();
                return;
            }

            if (File.Exists(fileTextBox.Text) && MessageBox.Show(this, string.Format(ResourceUtils.GetString("export", 9), fileTextBox.Text), ResourceUtils.GetString("common", 1), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
            {
                return;
            }

            ArrayList ids = null;
            if (selectedMoviesRadioButton.Checked)
            {
                ids = new ArrayList();
                if (SelectedMovies != null && SelectedMovies.Count > 0)
                {
                    foreach (MovieInfo movieInfo in SelectedMovies)
                    {
                        ids.Add(movieInfo.Id);
                    }
                }
                else
                {
                    ids.Add(0);
                }
            }
            ArrayList movies = MovieServiceFactory.getMovieService().FindMovieInfoByIds(ids);

            string delimiter = "";
            switch (GetSelectedIndex(m_delimeterButtonGroup))
            {
                case 0: delimiter = ";";
                    break;
                case 1: delimiter = ",";
                    break;
                case 2: delimiter = "\t";
                    break;
                case 3: delimiter = " ";
                    break;
            }

            string qualifier = "";
            switch (GetSelectedIndex(m_qualifierButtonGroup))
            {
                case 0: qualifier = "\"";
                    break;
                case 1: qualifier = "'";
                    break;
                case 2: delimiter = "";
                    break;
            }

            string lineBreak = "";
            switch (GetSelectedIndex(m_lineBreaksButtonGroup))
            {
                case 0: lineBreak = " ";
                    break;
                case 1: lineBreak = "\\n";
                    break;
                case 2: lineBreak = "";
                    break;
            }

            ConfigurationWrapper wrapper = new ConfigurationWrapper();
            TextExporter textExporter = new TextExporter(movies, fileTextBox.Text, ((EncodingInfo)encodingComboBox.SelectedItem).Name, fieldNamesCheckBox.Checked, delimiter, qualifier, lineBreak, wrapper.TextExportSection.Fields);

            using (ProgressWorker progressWorker = new ProgressWorker(textExporter))
            {
                progressWorker.Start();
            }

            DialogResult = DialogResult.OK;
            Close();
        }

        private void UpdateUI()
        {
            this.Text = ResourceUtils.GetString("textExport", 0);
            fileLabel.Text = ResourceUtils.GetString("textExport", 1);
            browseButton.Text = ResourceUtils.GetString("textExport", 2);
            fieldNamesCheckBox.Text = ResourceUtils.GetString("textExport", 3);
            delimeterGroupBox.Text = ResourceUtils.GetString("textExport", 4);
            semicolonRadioButton.Text = ResourceUtils.GetString("textExport", 5);
            commaRadioButton.Text = ResourceUtils.GetString("textExport", 6);
            tabRadioButton.Text = ResourceUtils.GetString("textExport", 7);
            spaceRadioButton.Text = ResourceUtils.GetString("textExport", 8);
            textQualifierGroupBox.Text = ResourceUtils.GetString("textExport", 9);
            doubleQuoteRadioButton.Text = ResourceUtils.GetString("textExport", 10);
            singleQuoteRadioButton.Text = ResourceUtils.GetString("textExport", 11);
            noneRadioButton.Text = ResourceUtils.GetString("textExport", 12);
            lineBreaksGroupBox.Text = ResourceUtils.GetString("textExport", 13);
            replaceSpaceRadioButton.Text = ResourceUtils.GetString("textExport", 14);
            replaceNewLineRadioButton.Text = ResourceUtils.GetString("textExport", 15);
            replaceNoneRadioButton.Text = ResourceUtils.GetString("textExport", 16);
            fieldsButton.Text = ResourceUtils.GetString("textExport", 17);
            encodingLabel.Text = ResourceUtils.GetString("textExport", 19);

            moviesGroupBox.Text = ResourceUtils.GetString("export", 0);
            allMoviesRadioButton.Text = ResourceUtils.GetString("export", 1);
            selectedMoviesRadioButton.Text = ResourceUtils.GetString("export", 2);
            exportButton.Text = ResourceUtils.GetString("export", 3);
            cancelButton.Text = ResourceUtils.GetString("export", 4);
        }

        public int CompareEncodingInfo(EncodingInfo x, EncodingInfo y)
        {
            return x.DisplayName.CompareTo(y.DisplayName);
        }
    }
}
